import DataBus from '../databus'
import SimpleCloudManager from '../network/simpleCloudManager'
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render'

export default class OnlineMenu {
  constructor() {
    this.isVisible = false
    this.databus = new DataBus()
    this.cloudManager = new SimpleCloudManager()
    
    // 按钮区域
    this.createRoomButton = {
      x: SCREEN_WIDTH / 2 - 100,
      y: SCREEN_HEIGHT / 2 - 40,
      width: 200,
      height: 50
    }
    
    this.joinRoomButton = {
      x: SCREEN_WIDTH / 2 - 100,
      y: SCREEN_HEIGHT / 2 + 20,
      width: 200,
      height: 50
    }
    
    this.backButton = {
      x: SCREEN_WIDTH / 2 - 100,
      y: SCREEN_HEIGHT / 2 + 80,
      width: 200,
      height: 50
    }
    
    // 回调函数
    this.gameStartCallback = null
    this.roomCreatedCallback = null
    this.roomJoinedCallback = null
    this.returnToMainMenuCallback = null
    
    // 状态
    this.isCreatingRoom = false
    this.isJoiningRoom = false
    this.isRoomCreator = false // 新增：标识是否为房间创建者
    this.roomId = null
    this.shareInfo = null
    
    this.setupCloudCallbacks()
  }

  setupCloudCallbacks() {
    // 设置云开发回调
    this.cloudManager.onRoomCreated = (roomId, isCreator) => {
      console.log('房间创建回调触发:', { roomId, isCreator })
      this.roomId = roomId
      this.isRoomCreator = isCreator // 设置创建者标志
      this.shareInfo = this.cloudManager.getShareLink()
      
      if (this.roomCreatedCallback) {
        this.roomCreatedCallback(roomId, isCreator)
      }
      
      // 只有创建房间时才显示分享提示
      if (isCreator) {
        this.showSharePrompt()
      }
    }
    
    this.cloudManager.onRoomJoined = (roomId, isCreator) => {
      console.log('房间加入回调触发:', { roomId, isCreator })
      this.roomId = roomId
      this.isRoomCreator = isCreator // 设置创建者标志
      
      // 设置在线模式状态
      // 房主是黑子(1)，加入者是白子(2) - 与云函数逻辑保持一致
      if (this.databus) {
        this.databus.setOnlineMode(true, isCreator ? 1 : 2)
        this.databus.setRoomId(roomId)
        this.databus.setOpponentConnected(false)
      }
      
      if (this.roomJoinedCallback) {
        this.roomJoinedCallback(roomId, isCreator)
      }
    }
    
    this.cloudManager.onGameStart = () => {
      console.log('游戏开始回调触发 - 两个玩家都已连接')
      
      // 设置游戏状态
      if (this.databus) {
        this.databus.setOpponentConnected(true)
        this.databus.setGameStarted(true)
      }
      
      // 隐藏在线菜单，显示游戏界面
      this.hide()
      
      if (this.gameStartCallback) {
        this.gameStartCallback()
      }
    }
    
    this.cloudManager.onOpponentConnected = () => {
      console.log('对手连接回调触发')
      wx.showToast({
        title: '对手已连接',
        icon: 'success'
      })
    }
    
    this.cloudManager.onGameOver = (winner) => {
      console.log('游戏结束回调触发:', winner)
      let content = ''
      if (winner === 0) {
        content = '游戏平局！'
      } else {
        const isWinner = winner === this.cloudManager.playerId
        content = isWinner ? '恭喜你赢了！' : '很遗憾，你输了'
      }
      wx.showModal({
        title: '游戏结束',
        content: content,
        showCancel: false,
        success: () => {
          this.returnToMainMenu()
        }
      })
    }
  }

  render(ctx) {
    if (!this.isVisible) return
    
    // 绘制半透明背景
    const gradient = ctx.createLinearGradient(0, 0, 0, SCREEN_HEIGHT)
    gradient.addColorStop(0, 'rgba(0, 0, 0, 0.7)')
    gradient.addColorStop(1, 'rgba(0, 0, 0, 0.5)')
    ctx.fillStyle = gradient
    ctx.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
    
    // 绘制标题
    ctx.fillStyle = '#fff'
    ctx.font = 'bold 28px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('在线对战', SCREEN_WIDTH / 2, 100)
    
    // 绘制按钮
    this.drawButtons(ctx)
    
    // 绘制说明文字
    this.drawInstructions(ctx)
    
    // 绘制房间信息（只有创建者才显示）
    if (this.roomId && this.isRoomCreator) {
      this.drawRoomInfo(ctx)
    }
  }

  drawButtons(ctx) {
    // 绘制创建房间按钮
    const createText = this.isCreatingRoom ? '创建中...' : '创建房间'
    this.drawButton(ctx, this.createRoomButton, '#4CAF50', '#45a049', createText, '#ffffff')
    
    // 绘制加入房间按钮
    const joinText = this.isJoiningRoom ? '加入中...' : '加入房间'
    this.drawButton(ctx, this.joinRoomButton, '#2196F3', '#1976D2', joinText, '#ffffff')
    
    // 绘制返回按钮
    this.drawButton(ctx, this.backButton, '#FF9800', '#F57C00', '返回主菜单', '#ffffff')
  }

  drawButton(ctx, button, color, hoverColor, text, textColor) {
    // 按钮阴影
    ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
    ctx.fillRect(button.x + 4, button.y + 4, button.width, button.height)
    
    // 按钮背景渐变
    const gradient = ctx.createLinearGradient(button.x, button.y, button.x, button.y + button.height)
    gradient.addColorStop(0, color)
    gradient.addColorStop(1, hoverColor)
    ctx.fillStyle = gradient
    
    // 圆角矩形
    this.drawRoundedRect(ctx, button.x, button.y, button.width, button.height, 12)
    
    // 按钮文字
    ctx.fillStyle = textColor
    ctx.font = 'bold 20px Arial'
    ctx.textAlign = 'center'
    ctx.fillText(text, button.x + button.width / 2, button.y + button.height / 2 + 6)
  }

  drawRoundedRect(ctx, x, y, width, height, radius) {
    ctx.beginPath()
    ctx.moveTo(x + radius, y)
    ctx.lineTo(x + width - radius, y)
    ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
    ctx.lineTo(x + width, y + height - radius)
    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
    ctx.lineTo(x + radius, y + height)
    ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
    ctx.lineTo(x, y + radius)
    ctx.quadraticCurveTo(x, y, x + radius, y)
    ctx.closePath()
    ctx.fill()
  }

  drawInstructions(ctx) {
    ctx.fillStyle = '#fff'
    ctx.font = '16px Arial'
    ctx.textAlign = 'center'
    
    // 添加图标或装饰
    const iconY = SCREEN_HEIGHT - 220
    const iconSize = 24
    
    // 绘制装饰性图标
    ctx.fillStyle = 'rgba(255, 255, 255, 0.3)'
    ctx.beginPath()
    ctx.arc(SCREEN_WIDTH / 2 - 100, iconY, iconSize / 2, 0, 2 * Math.PI)
    ctx.fill()
    ctx.beginPath()
    ctx.arc(SCREEN_WIDTH / 2 + 100, iconY, iconSize / 2, 0, 2 * Math.PI)
    ctx.fill()
    
    const instructions = [
      '创建房间后可以邀请好友对战',
      '点击复制按钮将房间号发送给好友',
      '好友输入房间号即可加入房间开始游戏'
    ]
    
    instructions.forEach((text, index) => {
      ctx.fillText(text, SCREEN_WIDTH / 2, SCREEN_HEIGHT - 180 + index * 25)
    })
  }

  drawRoomInfo(ctx) {
    // 绘制房间信息卡片
    const cardWidth = 320
    const cardHeight = 200
    const cardX = (SCREEN_WIDTH - cardWidth) / 2
    const cardY = 120
    
    // 卡片阴影
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
    ctx.fillRect(cardX + 4, cardY + 4, cardWidth, cardHeight)
    
    // 卡片背景渐变
    const gradient = ctx.createLinearGradient(cardX, cardY, cardX, cardY + cardHeight)
    gradient.addColorStop(0, 'rgba(255, 255, 255, 0.95)')
    gradient.addColorStop(1, 'rgba(248, 249, 250, 0.95)')
    ctx.fillStyle = gradient
    this.drawRoundedRect(ctx, cardX, cardY, cardWidth, cardHeight, 16)
    
    // 卡片边框
    ctx.strokeStyle = 'rgba(76, 175, 80, 0.3)'
    ctx.lineWidth = 1
    ctx.strokeRect(cardX, cardY, cardWidth, cardHeight)
    
    // 成功图标背景
    const iconSize = 40
    const iconX = cardX + cardWidth / 2 - iconSize / 2
    const iconY = cardY + 20
    
    // 图标背景圆
    ctx.fillStyle = '#4CAF50'
    ctx.beginPath()
    ctx.arc(iconX + iconSize / 2, iconY + iconSize / 2, iconSize / 2, 0, 2 * Math.PI)
    ctx.fill()
    
    // 成功图标（对勾）
    ctx.strokeStyle = '#ffffff'
    ctx.lineWidth = 3
    ctx.lineCap = 'round'
    ctx.beginPath()
    ctx.moveTo(iconX + 12, iconY + 20)
    ctx.lineTo(iconX + 18, iconY + 26)
    ctx.lineTo(iconX + 28, iconY + 16)
    ctx.stroke()
    
    // 标题
    ctx.fillStyle = '#2c3e50'
    ctx.font = 'bold 20px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('房间创建成功', cardX + cardWidth / 2, cardY + 90)
    
    // 房间号标签
    ctx.fillStyle = '#7f8c8d'
    ctx.font = '14px Arial'
    ctx.fillText('房间号', cardX + cardWidth / 2, cardY + 115)
    
    // 房间号显示框
    const roomIdBox = {
      x: cardX + 40,
      y: cardY + 125,
      width: cardWidth - 80,
      height: 35
    }
    
    // 房间号背景
    ctx.fillStyle = '#f8f9fa'
    ctx.strokeStyle = '#e9ecef'
    ctx.lineWidth = 1
    this.drawRoundedRect(ctx, roomIdBox.x, roomIdBox.y, roomIdBox.width, roomIdBox.height, 8)
    ctx.strokeRect(roomIdBox.x, roomIdBox.y, roomIdBox.width, roomIdBox.height)
    
    // 房间号文字
    ctx.fillStyle = '#2c3e50'
    ctx.font = 'bold 16px Arial'
    ctx.textAlign = 'center'
    ctx.fillText(this.roomId, roomIdBox.x + roomIdBox.width / 2, roomIdBox.y + 22)
    
    // 复制按钮
    const copyButton = {
      x: cardX + cardWidth / 2 - 60,
      y: cardY + cardHeight - 35,
      width: 120,
      height: 36
    }
    
    // 按钮渐变
    const buttonGradient = ctx.createLinearGradient(copyButton.x, copyButton.y, copyButton.x, copyButton.y + copyButton.height)
    buttonGradient.addColorStop(0, '#4CAF50')
    buttonGradient.addColorStop(1, '#45a049')
    ctx.fillStyle = buttonGradient
    this.drawRoundedRect(ctx, copyButton.x, copyButton.y, copyButton.width, copyButton.height, 18)
    
    // 按钮文字
    ctx.fillStyle = '#ffffff'
    ctx.font = 'bold 16px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('复制房间号', copyButton.x + copyButton.width / 2, copyButton.y + 22)
    
    // 提示文字
    ctx.fillStyle = '#ffffff'
    ctx.font = 'bold 16px Arial'
    ctx.fillText('点击复制房间号发送给好友', cardX + cardWidth / 2, cardY + cardHeight + 30)
  }

  handleTouch(x, y) {
    if (!this.isVisible) return false
    
    // 检查创建房间按钮
    if (this.isPointInButton(x, y, this.createRoomButton) && !this.isCreatingRoom) {
      this.createRoom()
      return true
    }
    
    // 检查加入房间按钮
    if (this.isPointInButton(x, y, this.joinRoomButton) && !this.isJoiningRoom) {
      this.joinRoom()
      return true
    }
    
    // 检查返回按钮
    if (this.isPointInButton(x, y, this.backButton)) {
      this.returnToMainMenu()
      return true
    }
    
    // 检查复制房间号按钮（只有创建者才能看到）
    if (this.roomId && this.isRoomCreator) {
      const cardWidth = 320
      const cardHeight = 200
      const cardX = (SCREEN_WIDTH - cardWidth) / 2
      const cardY = 120
      
      const copyButton = {
        x: cardX + cardWidth / 2 - 60,
        y: cardY + cardHeight - 45,
        width: 120,
        height: 36
      }
      
      if (this.isPointInButton(x, y, copyButton)) {
        // 直接复制房间号到剪贴板
        this.copyRoomId()
        return true
      }
    }
    
    return false
  }

  isPointInButton(x, y, button) {
    return x >= button.x && x <= button.x + button.width &&
           y >= button.y && y <= button.y + button.height
  }

  show() {
    this.isVisible = true
    this.roomId = null
    this.shareInfo = null
    this.isRoomCreator = false // 重置创建者标志
  }

  hide() {
    this.isVisible = false
  }

  async createRoom() {
    if (this.isCreatingRoom) return
    
    this.isCreatingRoom = true
    
    try {
      wx.showLoading({
        title: '创建房间中...'
      })
      
      await this.cloudManager.createRoom()
      
      wx.hideLoading()
      wx.showToast({
        title: '房间创建成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('创建房间失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '创建房间失败',
        icon: 'none'
      })
    } finally {
      this.isCreatingRoom = false
    }
  }

  async joinRoom() {
    if (this.isJoiningRoom) return
    
    this.isJoiningRoom = true
    
    try {
      // 弹出输入框让用户输入房间号
      const result = await new Promise((resolve, reject) => {
        wx.showModal({
          title: '加入房间',
          content: '请输入房间号',
          editable: true,
          placeholderText: '请输入房间号',
          success: (res) => {
            if (res.confirm && res.content) {
              resolve(res.content.trim())
            } else {
              reject(new Error('未输入房间号'))
            }
          },
          fail: reject
        })
      })
      
      console.log('用户输入的房间号:', result)
      
      // 验证房间号格式
      if (!result || result.length < 5) {
        throw new Error('房间号格式不正确')
      }
      
      wx.showLoading({
        title: '加入房间中...'
      })
      
      // 调用云函数加入房间
      await this.cloudManager.joinRoom(result)
      
      wx.hideLoading()
      wx.showToast({
        title: '成功加入房间',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('加入房间失败:', error)
      wx.hideLoading()
      
      // 根据错误类型显示不同的提示
      let errorMessage = '加入房间失败'
      if (error.message.includes('房间不存在')) {
        errorMessage = '房间不存在，请检查房间号'
      } else if (error.message.includes('房间已满')) {
        errorMessage = '房间已满，无法加入'
      } else if (error.message.includes('房间号格式')) {
        errorMessage = '房间号格式不正确'
      } else if (error.message.includes('自己创建')) {
        errorMessage = '不能加入自己创建的房间'
      } else if (error.message.includes('网络')) {
        errorMessage = '网络连接失败，请重试'
      } else {
        errorMessage = error.message || '加入房间失败'
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    } finally {
      this.isJoiningRoom = false
    }
  }

  showSharePrompt() {
    wx.showModal({
      title: '邀请好友',
      content: '房间已创建，点击分享按钮复制房间号\n\n将房间号发送给好友，好友输入房间号即可加入游戏',
      showCancel: false,
      confirmText: '知道了'
    })
  }

  // 手动分享房间号
  // 直接复制房间号到剪贴板
  copyRoomId() {
    if (!this.roomId) {
      wx.showToast({
        title: '房间号不存在',
        icon: 'none'
      })
      return
    }
    
    // 直接复制到剪贴板，不显示确认对话框
    wx.setClipboardData({
      data: this.roomId,
      success: () => {
        wx.showToast({
          title: '房间号已复制',
          icon: 'success',
          duration: 2000
        })
      },
      fail: (error) => {
        console.error('复制失败:', error)
        // 如果复制失败，显示房间号让用户手动复制
        wx.showModal({
          title: '复制失败',
          content: `请手动复制房间号：${this.roomId}`,
          showCancel: false,
          confirmText: '知道了'
        })
      }
    })
  }

  manualShareRoom() {
    if (!this.roomId) {
      wx.showToast({
        title: '房间号不存在',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '邀请好友',
      content: `房间号：${this.roomId}\n\n请将房间号发送给好友，好友输入房间号即可加入游戏`,
      showCancel: true,
      cancelText: '取消',
      confirmText: '复制房间号',
      success: (res) => {
        if (res.confirm) {
          // 复制房间号到剪贴板
          wx.setClipboardData({
            data: this.roomId,
            success: () => {
              wx.showToast({
                title: '房间号已复制',
                icon: 'success'
              })
            },
            fail: (error) => {
              console.error('复制失败:', error)
              // 如果复制失败，显示房间号让用户手动复制
              wx.showModal({
                title: '复制失败',
                content: `请手动复制房间号：${this.roomId}`,
                showCancel: false,
                confirmText: '知道了'
              })
            }
          })
        }
      }
    })
  }

  shareRoom() {
    if (!this.roomId) return
    
    try {
      // 直接使用手动分享，避免API调用问题
      this.manualShareRoom()
    } catch (error) {
      console.error('分享功能调用失败:', error)
      // 降级处理：显示分享信息
      this.showShareInfo()
    }
  }

  // 显示分享信息
  showShareInfo() {
    if (!this.roomId) return
    
    wx.showModal({
      title: '邀请好友',
      content: `房间号：${this.roomId}\n\n请将房间号发送给好友，好友输入房间号即可加入游戏`,
      showCancel: false,
      confirmText: '知道了'
    })
  }

  returnToMainMenu() {
    this.hide()
    this.cloudManager.cleanup()
    
    if (this.returnToMainMenuCallback) {
      this.returnToMainMenuCallback()
    }
  }

  setGameStartCallback(callback) {
    this.gameStartCallback = callback
  }

  setRoomCreatedCallback(callback) {
    this.roomCreatedCallback = callback
  }

  setRoomJoinedCallback(callback) {
    this.roomJoinedCallback = callback
  }

  setReturnToMainMenuCallback(callback) {
    this.returnToMainMenuCallback = callback
  }

  getCloudManager() {
    return this.cloudManager
  }

  update() {
    // 更新逻辑
  }

  // 自动加入房间
  async autoJoinRoom(roomId) {
    if (this.isJoiningRoom) return
    
    this.isJoiningRoom = true
    
    try {
      await this.cloudManager.joinRoom(roomId)
      wx.showToast({
        title: '成功加入房间',
        icon: 'success'
      })
    } catch (error) {
      console.error('自动加入房间失败:', error)
      wx.showToast({
        title: error.message || '加入房间失败',
        icon: 'none'
      })
    } finally {
      this.isJoiningRoom = false
    }
  }

  // 获取分享信息（用于页面分享）
  getShareInfo() {
    if (!this.roomId) {
      return {
        title: '五子棋 - 经典对战游戏',
        path: '/pages/game',
        imageUrl: '/images/share.jpg'
      }
    }
    
    return {
      title: '来和我下五子棋吧！',
      path: `/pages/game?roomId=${this.roomId}`,
      imageUrl: '/images/share.jpg'
    }
  }

  // 获取在线菜单实例
  getOnlineMenu() {
    return this
  }
  
  // 调试方法：手动触发游戏开始（仅用于测试）
  debugTriggerGameStart() {
    console.log('手动触发游戏开始（调试模式）')
    if (this.cloudManager && this.cloudManager.onGameStart) {
      this.cloudManager.gameStarted = true
      this.cloudManager.onGameStart()
    }
  }

  // 手动检查游戏状态
  async debugCheckGameStatus() {
    if (!this.cloudManager || !this.roomId) {
      console.log('没有云管理器或房间ID')
      return
    }
    
    try {
      console.log('手动检查游戏状态...')
      const result = await this.cloudManager.callCloudFunction('get_room_info', {
        roomId: this.roomId
      })
      
      if (result.success) {
        console.log('当前房间状态:', result.data)
        
        // 如果房间状态是playing，手动触发游戏开始
        if (result.data.status === 'playing') {
          console.log('房间状态为playing，手动触发游戏开始')
          if (this.cloudManager.onGameStart) {
            this.cloudManager.onGameStart()
          }
        }
      }
    } catch (error) {
      console.error('检查游戏状态失败:', error)
    }
  }
} 